package com.app.studyroom.adapter;

import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;  // ✅ 新增：删除按钮
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.app.studyroom.R;
import com.app.studyroom.api.ApiClient;
import com.app.studyroom.api.ApiResponse;
import com.app.studyroom.api.ApiService;
import com.app.studyroom.api.model.ssrSeat.SsrSeatBooking;
import com.app.studyroom.api.model.ssrUser.UserIdRequest;
import com.app.studyroom.db.UserInfo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class BookingRecordAdapter extends RecyclerView.Adapter<BookingRecordAdapter.ViewHolder> {

    // ✅ 接口：用于回调删除操作
    public interface OnDeleteListener {
        void onDelete(String recordId);
    }

    private final List<SsrSeatBooking> bookingList;
    private final OnDeleteListener deleteListener;

    // ✅ 添加：用户名缓存和主线程 handler
    private final Map<String, String> userNameCache = new HashMap<>();
    private final Handler uiHandler = new Handler(Looper.getMainLooper());

    // ✅ 构造函数支持删除监听器
    public BookingRecordAdapter(List<SsrSeatBooking> bookingList, OnDeleteListener deleteListener) {
        this.bookingList = bookingList;
        this.deleteListener = deleteListener;
    }

    @NonNull
    @Override
    public BookingRecordAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_booking_record, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull BookingRecordAdapter.ViewHolder holder, int position) {
        SsrSeatBooking booking = bookingList.get(position);

        // ✅ 格式化时间
        String startTime = booking.getBookingStartTime();
        String endTime = booking.getBookingEndTime();
        String startDisplay = startTime != null && startTime.length() >= 16 ? startTime.substring(5, 16) : startTime;
        String endDisplay = endTime != null && endTime.length() >= 16 ? endTime.substring(5, 16) : endTime;
        holder.tvTime.setText(startDisplay + " - " + endDisplay);
        holder.tvStatus.setText(booking.getApprovalStatusText());
        // ✅ 删除按钮逻辑（传 bookingId）
        holder.btnDelete.setOnClickListener(v -> {
            if (deleteListener != null && booking.getId() != null) {
                deleteListener.onDelete(booking.getId()); //此ID是记录的ID，不是 bookingId
            }
        });

        //由用户id获取用户名字
        String userId = booking.getBookingUser();
        holder.tvUser.setText("加载中...");
        // 已缓存用户名
        if (userNameCache.containsKey(userId)) {
            holder.tvUser.setText(userNameCache.get(userId));
        } else {
            // 未缓存，异步加载
            ApiService apiService = ApiClient.getClient().create(ApiService.class);
            apiService.getUserById(new UserIdRequest(Long.parseLong(userId))).enqueue(new Callback<ApiResponse<UserInfo>>() {
                @Override
                public void onResponse(Call<ApiResponse<UserInfo>> call, Response<ApiResponse<UserInfo>> response) {
                    if (response.isSuccessful() && response.body() != null && response.body().getData() != null) {
                        String userName = response.body().getData().getUserName();
                        userNameCache.put(userId, userName);
                        uiHandler.post(() -> holder.tvUser.setText(userName));
                    } else {
                        uiHandler.post(() -> holder.tvUser.setText("未知用户"));
                    }
                }

                @Override
                public void onFailure(Call<ApiResponse<UserInfo>> call, Throwable t) {
                    uiHandler.post(() -> holder.tvUser.setText("加载失败"));
                }
            });
        }

    }

    @Override
    public int getItemCount() {
        return bookingList != null ? bookingList.size() : 0;
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvTime, tvUser, tvStatus;
        Button btnDelete;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvTime = itemView.findViewById(R.id.tv_time);
            tvUser = itemView.findViewById(R.id.tv_booking_user);
            tvStatus = itemView.findViewById(R.id.tv_booking_status);
            btnDelete = itemView.findViewById(R.id.btn_delete_booking);
        }
    }
}
